<template>
  <div class="users-base-wrapper">
    <div class="module-name">
      <div>
        <span style="display: inline-block; border-left: 4px solid #753cca; line-height: 25px; padding-left: 12px;">界面设计({{ queryParams.name }})</span>
      </div>
      <el-button size="mini" type="default" icon="el-icon-arrow-left" @click="handleGoBack">返回上一级</el-button>
    </div>
    <div class="details-layout">
      <el-row style="text-align: left; margin-bottom: 16px;">
        <el-button type="primary" size="mini" @click="handleRefresh" icon="el-icon-refresh">刷新</el-button>
        <el-button type="primary" size="mini" @click="handleAdd" v-if="isOperate" icon="el-icon-plus">新增</el-button>
        <el-button type="primary" size="mini" @click="handleRestoreDefault" v-if="isOperate" icon="el-icon-refresh-left">恢复默认</el-button>
        <el-button type="primary" size="mini" @click="handlePreview" icon="el-icon-view">界面预览</el-button>
      </el-row>
      <el-table :data="interfacialList" stripe style="width: 100%" size="mini" row-key="id"
                :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }" :tree-props="{ children: 'children' }">
        <el-table-column
          type="index"
          label="序号"
          width="50">
        </el-table-column>
        <template v-for="(column, index) in tableColumns">
          <el-table-column v-if="column.visible" :width="column.width" :key="index" :min-width="column.minWidth" 
                           :label="column.name" :show-overflow-tooltip="true" align="center">
            <template slot-scope="scope">
              <!-- 编辑 -->
              <div v-if="column.key === 'edit'">
                <i class="el-icon-edit table-icon" @click="handleEdit(scope.row)" v-if="isOperate"></i>
                <span v-else>/</span>
              </div>
              <!-- 删除 -->
              <div v-if="column.key === 'delete'">
                <i class="el-icon-delete table-icon" @click="handleDelete(scope.row)" v-if="isOperate"></i>
                <span v-else>/</span>
              </div>
              <div v-if="column.key === 'sort1'">
                <i class="el-icon-sort table-icon" @click="handleSort(scope.row)" v-if="isOperate"></i>
                <span v-else>/</span>
              </div>
              <div v-if="column.key === 'hideColumn'">
                <span>{{ scope.row.hide === '1' ? '是' : '否'}}</span>
              </div>
              <div v-if="column.key === 'variableType1'">
                <span>{{ variableTypeEnumeration[scope.row.variableType] }}</span>
              </div>
              <div v-if="column.key === 'type1'">
                <span>{{ typeEnumeration[scope.row.type] }}</span>
              </div>
              <div v-if="column.key === 'variableName1'">
                <span>{{ scope.row.type === '3' ? scope.row.embeddedSurfaceName : scope.row.variableName }}</span>
              </div>
              <div v-if="column.key === 'rowControlJson1'">
                <el-button type="text" v-if="(scope.row.variableType === '10' || scope.row.variableType === '20') && finallyId !== scope.row.id" @click="handleOpenRowControl(scope.row)">
                  {{ scope.row.rowControl && scope.row.rowControl.length > 0 ? '已设置' : '未设置' }}
                </el-button>
                <span v-else>/</span>
              </div>
              <span v-else>{{ scope.row[column.key] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <add-record 
        :dialogVisible="dialogVisible" 
        :dialogTitle="dialogTitle" 
        :editData="editData"
        @handleCancel="handleCancel"
        :searchParams="searchParams">
      </add-record>
      <sortData :sortVisible="sortVisible" :sortData="sortData" :sortList="sortList" @handleSortCancel="handleSortCancel"></sortData>
      <rowControl :isOperate="isOperate" :rowVisible="rowVisible" :rowData="rowData" @handleCancel="handleRowControlCancel" :tableColumns="columnData" :baseParams="baseParams" :controlList="controlList"></rowControl>
      <preview-form :formVisible="formVisible" @handlePreviewCancel="handlePreviewCancel" :previewVariableList="previewVariableList"></preview-form>
    </div>
  </div>
</template>
<script>

import { mapActions } from 'vuex'
import { tableColumns, typeEnumeration } from './data'
import addRecord from './component/add-interfacial.vue'
import sortData from './component/sort.vue'
import rowControl from './component/row-control.vue'
import { cloneDeep } from 'lodash-es'
import { variableTypeEnumeration } from '@/utils/enums/ecrf-design.js'
import previewForm from './component/preview-form.vue'

export default {
  name: 'interfacial-design',
  components: {
    addRecord,
    sortData,
    rowControl,
    previewForm
  },

  data() {
    return {
      dialogVisible: false,
      dialogTitle: '',
      editData: {},
      interfacialList: [],
      tableColumns,
      sortVisible: false,
      sortData: {},
      sortList: [],
      searchParams: {},
      queryParams: {},
      typeEnumeration,
      variableTypeEnumeration,
      finallyId: '',
      rowVisible: false,
      columnData: [],
      baseParams: '',
      controlList: [],
      formVisible: false,
      previewVariableList: [],
      rowData: {},
      isOperate: true
    }
  },
  mounted() {
    this.queryParams = this.$route.query
    const databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}
    this.searchParams = {
      projectId: localStorage.getItem('sys-project-id') || '',
      ...databaseInfo,
      surface: this.queryParams.surface
    }

    if (databaseInfo.isLock === '1') {
      this.isOperate = false
    }

    this.getInterfacialList()
  },

  methods: {
    ...mapActions('eCRFDesign', ['qryInterfaceDesignList', 'deleteInterfaceDesign', 'restoreInterfaceDesign', 'qryCodeValueByCodeName', 'qryInterfaceVariablesPreviewList']),

    // 查询界面设计列表
    getInterfacialList() {
      const params = {
        ...this.searchParams
      }
      this.qryInterfaceDesignList({ params }).then((res) => {
        const { data, code, message } = res
        if (code === 200) {
          this.interfacialList = data
          if (data.length > 0) {
            this.finallyId = data[data.length - 1].id
          }
        } else {
          this.$message.error(message || '服务异常，请稍后重试!')
        }
      })
    },

    // 返回上一级目录
    handleGoBack() {
      this.$router.go(-1)
    },

    // 界面预览 
    handlePreview() {
      this.getInterfaceVariablesPreviewList()
    },

    // 查询预览字段
    getInterfaceVariablesPreviewList() {
      const params = {
        ...this.searchParams
      }
      this.qryInterfaceVariablesPreviewList({ params }).then((res) => {
        const { code, data } = res
        if (code === 200) {
          this.previewVariableList = data
          this.formVisible = true
        }
      })
    },

    // 关闭预览弹框
    handlePreviewCancel() {
      this.formVisible = false
    },

    // 打开行控制弹框
    handleOpenRowControl(row) {
      this.baseParams = row.variable
      this.rowData = row
      const list = []
      let flag = false
      this.interfacialList.map((iItem, iIndex) => {
        if (row.id === iItem.id) {
          flag = true
        }
        if (flag) {
          list.push(iItem)
        }
      })

      const column = []
      console.log('lItem.variableType', list)
      list.map((lItem, lIndex) => {
        if (lItem.variableType || lItem.embeddedSurface) {
          const obj = {
            key: lItem.variable || lItem.embeddedSurface,
            name: lItem.variableName,
            visible: true
          }
          column.push(obj)
        }
      })
      this.columnData = column
      console.log('this.columnData', this.columnData)
      const codeName = row.variableValue && row.variableValue.codeName ? row.variableValue.codeName.split('|')[0] : ''
      this.getCodeValueByCodeName(codeName, row)
    },

    // 根据编码名称获取编码值
    getCodeValueByCodeName(codeName, row) {
      const params = {
        ...this.searchParams,
        code_name: codeName
      }
      this.qryCodeValueByCodeName({ params }).then((res) => {
        const { data, code } = res
        if (code === 200) {
          data.map((dItem, dIndex) => {
            this.columnData.map((cItem, cIndex) => {
              dItem[cItem.key] = false
              dItem.variable = cItem.key
              dItem.variableName = cItem.name
              dItem.crfName = row.surface
              dItem.databaseId = params.databaseId
              dItem.databaseVersion = params.databaseVersion
              dItem.projectId = params.projectId
            })
          })
          this.controlList = data

          console.log('this.controlList', this.controlList)
          this.rowVisible = true
        }
      })
    },

    // 取消
    handleRowControlCancel(type) {
      this.rowVisible = false
      if (type === 'refresh') {
        this.getInterfacialList()
      }
    },

    // 恢复默认
    handleRestoreDefault () {
      const data = {
        ...this.searchParams
      }
      this.$confirm('请确认是否恢复默认设置（默认与字段同步）', '提示', {
        type: 'warning'
      }).then(res => {
        this.restoreInterfaceDesign({ data }).then((res) => {
          const { code } = res
          if (code === 200) {
            this.$message.success('操作成功!')
            this.getInterfacialList()
          }
        })
      })
    },

    // 刷新列表
    handleRefresh() {
      this.getInterfacialList()
    },

    // 新增界面设计
    handleAdd() {
      this.dialogVisible = true
      this.editData = {
        sort: this.interfacialList && this.interfacialList.length > 0 ? this.interfacialList[this.interfacialList.length - 1].sort + 1 : 0,
        hide: 0
      }
      this.dialogTitle = '新建'
    },

    // 打开排序弹框
    handleSort(record) {
      this.sortVisible = true
      this.sortData = record
      this.sortList = cloneDeep(this.interfacialList)
    },

    // 关闭
    handleSortCancel(type) {
      this.sortVisible = false
      if (type === 'refresh') { // 是刷新列表
        this.getInterfacialList()
      }
    },

    // 编辑
    handleEdit(record) {
      this.dialogTitle = '编辑'
      this.dialogVisible = true
      this.editData = {
        ...record,
        embeddedTable: record.embeddedSurface + '##' + record.embeddedSurfaceName
      }
    },

    // 关闭弹框
    handleCancel(type) {
      this.dialogVisible = false
      if (type === 'refresh') { // 是刷新列表
        this.getInterfacialList()
      }
    },

    // 删除
    handleDelete(row) {
      const params = {
        id: row.id
      }
      this.$confirm('确定删除该条数据吗？', '删除提示', {
        type: 'warning'
      }).then(res => {
        this.deleteInterfaceDesign({ params })
          .then(res => {
            if (res.code === 200) {
              this.$message({ message: '删除成功', type: 'success' })
              this.getInterfacialList()
            }
          })
      })
    }
  },
}
</script>
<style lang="scss" scoped>
@import './index.scss';
</style>
